
import request from '@/utils/request'
import { Notification,MessageBox } from 'element-ui'
import gvar from "@/api/ws/global.js"
import {createWebSocket} from "@/api/ws/sendwebsocket.js"

//done
export function sendcmd(deviceid, sCmd, str,is_type) {  
  let cmd='';
  //var topic ='';
  gvar.deviceid = deviceid

  switch(is_type){
      case 1:        
          cmd = 'cc#' + deviceid + '#{"messageid":' + messageid() + ',"timestamp":' + timestamp() + ',"deviceid":"' + deviceid + '","uid":"'+sessionStorage.getItem('socket_id')+'","app_type":"agent","cmd":"' + sCmd + '","desired":{' + str + '}}';
          createWebSocket().then(ws=>{
            console.log(cmd,ws,ws.readyState);
            ws.send(cmd)
          })    
          break;
      case 2:

          // if(deviceid==''){
          //     topic =  '/APP/'+ Socket_id +'/ADMIN/NOTIFIY';
          // }else{
          //     topic =  '/APP/'+ Socket_id +'/ADMIN/NOTIFIY/'+deviceid;
          // }

          // cmd = '{"messageid":' + messageid() + ',"timestamp":' + timestamp() + ',"deviceid":"' + deviceid + '","cmd":"' + sCmd + '","desired":{' + str + '}}';

          // _mqttws.publish(topic,cmd);
          // break;
  }
}

//down
function messageid() {
  // 8位随机数
  return Math.floor(Math.random() * (99999999 - 10000000)) + 10000000;
}

//down
function timestamp() {
  // 时间戳
  return parseInt(new Date().getTime() / 1000);
}

//down
export function opendevices(deviceid, sCmd, status,is_type) {
  let str = ''
  if (status == 0) {
      str = '您确定要对【' + deviceid + '】执行【一键全关】？'
  } else {
      str = '您确定要对【' + deviceid + '】执行【一键全开】？'
  }
  MessageBox.confirm(
    str,
    '系统提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    opendevicesoper(deviceid, sCmd, status,is_type);
  }).catch(() => { 
  })
}

//done 
//关闭或者打开单个开关 
export function opendeviceone(deviceid,lnid,sCmd,status,is_type) {     
    let strl = '{"device":{"id":' + lnid + '},"status":{"switch":' + status + '}}';
        strl = '"arrays":[' + strl + ']';
        sendcmd(deviceid, sCmd, strl,is_type);  
}

//done
export function opendevicesoper(deviceid, sCmd, status,is_type) {
  request({
    url:'ajax.subdevices/index',
    mothod:'post',
    params:{'deviceid': deviceid},    
  }).then(data=>{
    console.log(data);
    if (data.code == 1) {
      let ii = 0;
      let strl = '';

      data.data.forEach((item,index) =>{
        if (ii > 0) {
          strl = '{"device":{"id":' + item.lnid + '},"status":{"switch":' + status + '}},' + strl;
        } else {
          strl = '{"device":{"id":' + item.lnid + '},"status":{"switch":' + status + '}}';
        }
        ii++;
      })      
      if (ii > 0) {
          strl = '"arrays":[' + strl + ']';
          sendcmd(deviceid, sCmd, strl,is_type);
      }
  }
  }) 
}

//恢复出厂
export function resetdevices(deviceid, sCmd) {
  let str = '您确定要对【' + deviceid + '】恢复出厂设置？请慎重使用'
  MessageBox.confirm(
    str,
    '系统提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    //原来这个请求路径是不存在的 这个还是隐藏吧 在界面上，后面再说
    request({
      url:'ajax.devices/subdevice',
      mothod:'post',
      params:{'deviceid': deviceid},    
    }).then(res=>{
        //console.log(res,'试试')
        //原来的这个功能也没实现 
        //sendcmd(deviceid, sCmd, strl,1);    
    })   
  }).catch(() => { 
  })
}

//down
export function opertioncmd02(deviceid,lnid, cmdinfo, sCmd,is_type) {
  let strl = '"arrays":[{"device":{"id":' + lnid + '},"getsome":{"' + cmdinfo + '":1}}]';

  sendcmd(deviceid, sCmd, strl,is_type);
}

//获取开关基本信息
//down
export function opertioncmd01(deviceid,cmdinfo, sCmd,is_type) {
  let strl = '"' + cmdinfo + '":1';
  sendcmd(deviceid, sCmd, strl,is_type);
}

//排序
//down 
export function opertioncmd01sort(deviceid, sCmd,is_type){
  let strl = '"getallsort":1';
  sendcmd(deviceid, sCmd, strl,is_type);
}
//返回101
//开关上传基本信息 这是一个被动执行的函数
// function cmd101(received_msg) {
//   for (let i = 0; i < received_msg['desired']['arrays'].length; i++) {
//       if (received_msg['desired']['arrays'][i]) {
//           if (received_msg['desired']['arrays'][i]['status']) {
//               let voltage = received_msg['desired']['arrays'][i]['status']['voltage'];

//               let ln = received_msg['desired']['arrays'][i]['device']['id'];
//               for (let ii = 0; ii < voltage.length; ii++) {
//                   $('.power_' + ln + "_" + ii).html(received_msg['desired']['arrays'][i]['status']['power']);
//                   $('.current_' + ln + "_" + ii).html((received_msg['desired']['arrays'][i]['status']['current'][ii]/1000));
//                   $('.temp_' + ln + "_" + ii).html(received_msg['desired']['arrays'][i]['status']['temp']);
//                   $('.voltage_' + ln + "_" + ii).html(voltage[ii]);
//                   $('#usepower_' + ln + "_" + ii).show();
//               }
//               let txswitch = received_msg['desired']['arrays'][i]['status']['switch'];
//               let status = $("#" + ln).hasClass('close2');
//               if (txswitch == 1) {
//                   if (status != true) {
//                       $("#" + ln).parent().toggleClass('close1');
//                       $("#" + ln).parent().toggleClass('open1');
//                       $("#" + ln).toggleClass('close2');
//                       $("#" + ln).toggleClass('open2');
//                   }
//               } else {
//                   if (status == true) {
//                       $("#" + ln).parent().toggleClass('close1');
//                       $("#" + ln).parent().toggleClass('open1');
//                       $("#" + ln).toggleClass('close2');
//                       $("#" + ln).toggleClass('open2');
//                   }
//               }
//           }
//       }
//   }
// }

//返回102
//{"timestamp":1591785668,"deviceid":"TS527A051","cmd":"CMD-102","desired":{"arrays":[{"device":{"id":2006030026},"status":{"frequency":50,"electricity":0,"powerfactor":0,"nopower":0,"shortcircuitnum":0,"temp":28,"leakage":0,"version":"1.0.2","switch":0,"auto":0,"current":[0],"voltage":[0],"power":[0]}}]}}
// function cmd102(received_msg) {
//   let body = layer.getChildFrame('body').contents();
//   //let content = $("#loadmax").val();

//   let desiredArr = received_msg['desired']['arrays'];
//   for (let i = 0; i < desiredArr.length; i++) {
//       if (desiredArr[i]) {
//           if (desiredArr[i]['status']) {
//               let ln = desiredArr[i]['device']['id'];
//               $('.status_voltage' + ln +'A').html(desiredArr[i]['status']['voltage'][0] + 'V');//电压
//               $('.status_current' + ln+'A').html((desiredArr[i]['status']['current'][0]/1000) + 'A');//电流
//               if(desiredArr[i]['status']['voltage'].length >1){
//                   $('.status_voltage' + ln +'B').html(desiredArr[i]['status']['voltage'][1] + 'V');//电压
//                   $('.status_voltage' + ln +'C').html(desiredArr[i]['status']['voltage'][2] + 'V');//电压
//                   $('.status_current' + ln +'B').html((desiredArr[i]['status']['current'][1]/1000) + 'A');//电流
//                   $('.status_current' + ln +'C').html((desiredArr[i]['status']['current'][2]/1000) + 'A');//电流
//                   $('.status_voltage' + ln +'B').parent().show();
//                   $('.status_voltage' + ln +'C').parent().show();
//                   $('.status_current' + ln +'B').parent().show();
//                   $('.status_current' + ln +'C').parent().show();
//               }else{
//                   $('.status_voltage' + ln +'B').parent().hide();
//                   $('.status_voltage' + ln +'C').parent().hide();
//                   $('.status_current' + ln +'B').parent().hide();
//                   $('.status_current' + ln +'C').parent().hide();
//               }

//               $('.status_power' + ln).html(desiredArr[i]['status']['power'] + 'W');//有功功率
//               $('.status_nopower' + ln).html(desiredArr[i]['status']['nopower'] + 'W');//无功功率
//               $('.status_leakage' + ln).html(desiredArr[i]['status']['leakage'] + 'A');//漏电电流
//               $('.status_frequency' + ln).html(desiredArr[i]['status']['frequency'] + 'Hz');//频率
//               $('.status_electricity' + ln).html(desiredArr[i]['status']['electricity'] + 'Kwh');//电能
//               $('.status_temp' + ln).html(desiredArr[i]['status']['temp'] + '℃');//温度
//               $('.status_shortcircuitnum' + ln).html(desiredArr[i]['status']['shortcircuitnum'] + '次');//短路跳闸次数
//               $('.status_version' + ln).html(desiredArr[i]['status']['version']);//硬件版本号
//           }
//       }
//   }
// }

//返回104
// function cmd104(received_msg) {

//   let body = layer.getChildFrame('body').contents();
//   let content = $("#loadmax").val();
//   for (let i = 0; i < received_msg.length; i++) {
//       if (received_msg[i]) {
//           if (received_msg[i]['getparam']) {
//               $("#elecmax").val(received_msg[i]['getparam']['elecmax']);//电流
//               $("#loadmax").val(received_msg[i]['getparam']['loadmax']);//电压
//               $("#tempmax").val(received_msg[i]['getparam']['tempmax']);//漏电电流
//               $("#voltmax").val(received_msg[i]['getparam']['voltmax']);//温度
//               $("#voltmin").val(received_msg[i]['getparam']['voltmin']);//温度
//               if (received_msg[i]['getparam']['leakage']) {
//                   $('#leakage').attr('checked', 'true');//短路跳闸次数
//               }
//           }
//       }
//   }
// }

//返回110
//{"timestamp":1592303040,"deviceid":"TS527A051","cmd":"CMD-110","desired":{"arrays":[{"device":{"id":181002001},"status":[{"error":10,"value":0}]}]}
function cmd110(received_msg = {}, deviceid = null) {
  deviceid = (deviceid == null || deviceid == '') ? received_msg['deviceid'] : deviceid;
  let alarm_info_item = received_msg['desired']['arrays'][0];
  let lnid = alarm_info_item['device']['id'];
  new Promise(resolve => {
      $.post('/alarminfo/getAlarminfo', {deviceid, lnid}, function (res) {
          resolve(res);
      });
  }).then(res => {
      let title = res.title ? res.title : '';

      let create_at = formatTime2Date(received_msg['timestamp']);
      let event_params = JSON.stringify({
          'error_type': fauult_errortype[alarm_info_item['status'][0]['error']],
          create_at
      }).replace(/"/g, '&quot;');

      alarm_info_data.push({
          deviceid,
          title,
          'error_type': fauult_errortype[alarm_info_item['status'][0]['error']],
          'solution': {
              'type': 'link',
              'label': '查看',
              'event': "layui_tips($(this).children().html(),{'title': '设备：" + deviceid + " - 解决方案'})",
              'color': '#2e8ded',
              'content': solution[alarm_info_item['status'][0]['error']]
          },
          create_at,
          'action': {
              'type': 'button',
              'label': '已解决？',
              'event': `updateAlarmStatus('${deviceid}','${lnid}','${event_params}')`,
              'class': 'layui-btn-primary layui-btn-sm'
          }
      });

      alarm_info_popup(alarm_info_data);
  })
}

//报警弹窗
function alarm_info_popup(alarm_info_data) {
  if (alarm_info_data.length == 0) return false;

  const column_name_arr = {
      'deviceid': '设备ID',
      'title': '分路名称',
      'error_type': '故障类型',
      'solution': '解决方案',
      'create_at': '故障时间',
      'action': '标记状态'
  };

  let id = 'alarmInfo';//弹窗唯一标志

  //判断是否已经有弹窗，有则直接追加
  if (typeof (alarmInfo) != "undefined") {
      let alarm_el = $("#" + id).find('tbody');
      $("#" + id).css('height', '');
      const current_alarm_info = alarm_info_data[alarm_info_data.length - 1];
      alarm_el.append(buildLayuiListContent([current_alarm_info], column_name_arr));
      return false;
  }

  let btn_arr = [];
  if (alarm_info_data.length > 1) {
      btn_arr = [
          {'name': '查看更多', "bindEvent": "target_iFrame('/alarminfo/index.html','设备故障',5)"},
          {'name': '返回', 'bindEvent': 'close'},
      ];
  }

  return layui_list(alarm_info_data, column_name_arr, " 异常设备 - 报警信息", [], 'x', ['50%', 'auto'], btn_arr, id);
}

//格式化报警设备弹窗数据
function arrayToAlarmFormat(array = []) {
  result = [];

  $.each(array, function (index, item) {
      let create_at = item['create_at'] != undefined ? item['create_at'] : '-';
      let event_params = JSON.stringify({
          'title': item['title'],
          'error_type': fauult_errortype[item['alarm_erro']],
          create_at,
      }).replace(/"/g, '&quot;');

      result.push({
          'deviceid': item['deviceid'],
          'title': item['title'],
          'error_type': fauult_errortype[item['alarm_erro']],
          'solution': {
              'type': 'link',
              'label': '查看',
              'event': "layui_tips($(this).children().html(),{'title': '设备：" + item['deviceid'] + " - 解决方案'})",
              'color': '#2e8ded',
              'content': solution[item['alarm_erro']]
          },
          create_at,
          'action': {
              'type': 'button',
              'label': '已解决？',
              'event': `updateAlarmStatus('${item['deviceid']}','${item['lnid']}','${event_params}')`,
              'class': 'layui-btn-primary layui-btn-sm'
          }
      });
  });
  return result;
}

//更新报警设备的状态
function updateAlarmStatus(deviceid, lnid, params = "") {
  params = JSON.parse(params);
  let title = params.title;
  let error_type = params.error_type;
  let create_at = params.create_at;

  $.post("/subdevices/updateAlarmStauts", {deviceid, lnid}, function (res) {
      res = JSON.parse(res);
      layer.msg(res.msg);
      if (res.code == 1) {
          //删除tr节点
          let trArr = $("#alarmInfo").find('tbody>tr');
          $.each(trArr, function (i, item) {
              let currentTr = $("#alarmInfo").find(`tbody>tr:eq(${i})`);
              let deviceid_item = currentTr.find('td:eq(0)').html();
              let title_item = currentTr.find('td:eq(1)').html();
              let error_type_item = currentTr.find('td:eq(2)').html();
              let create_at_item = currentTr.find('td:eq(4)').html();
              if (deviceid_item == deviceid && title_item == title && error_type_item == error_type && create_at_item == create_at) {
                  currentTr.remove();
                  if ($("#alarmInfo").find('tbody>tr').length == 0) {
                      layer.close(layer.index);
                  }
              }
          });
          //找出该组数据
          const filterArr = _util.array.filter(alarm_info_data, {deviceid, lnid, error_type, create_at});
          //删除该组数据
          _util.array.remove(alarm_info_data, filterArr);
      }
  }, 'json');
}


//设备电流电压cmd4
//down
export function sendsubset(deviceid,ln,is_type,elecmax,currmax,loadmax,tempmax,voltmax,voltmin,leakage,leaktime) {
 let strl = '"arrays":[{"device":{"id":'+ ln +'},"setparam":{"elecmax":'+elecmax+',"currmax":'+currmax+',"loadmax":'+ loadmax +',"tempmax":'+ tempmax +',"voltmax":'+ voltmax +',"voltmin":'+ voltmin +',"leakage":'+ leakage +',"leaktime":"'+ leaktime +'"}}]';
 sendcmd(deviceid, 'CMD-4', strl,is_type);  
}


//cmd22
function cmd22(is_type) {
  let  strl = '"reset":1';
  sendcmd('', 'CMD-22', strl,is_type);
}